// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "FLTCookieManager.h"

@implementation FLTCookieManager {
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  FLTCookieManager *instance = [[FLTCookieManager alloc] init];

  FlutterMethodChannel *channel =
      [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/cookie_manager"
                                  binaryMessenger:[registrar messenger]];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
  if ([[call method] isEqualToString:@"clearCookies"]) {
      [self clearCookies:result];
  } else if ([[call method] isEqualToString:@"setCookies"]) {
      [self setCookies:call result:result];
  } else {
    result(FlutterMethodNotImplemented);
  }
}

- (void)setCookies:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSDictionary *info = call.arguments;
    NSString *url = info[@"url"];
    NSString *type = info[@"type"];
    NSString *token = info[@"token"];
    
    NSLog(@"url : %@ type: %@ token: %@", url, type, token);
    
    // 创建Request请求
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url?:@""]];
    // 设置请求方法
    [urlRequest setHTTPMethod:type?:@"GET"];
    // 设置请求超时 默认超时时间10s
    [urlRequest setTimeoutInterval:10.0];
    // 设置头部参数
    [urlRequest addValue:token?:@"" forHTTPHeaderField:@"token"];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
     
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {

//        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
//        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[httpResp allHeaderFields] forURL:[response URL]];
//        NSLog(@"header: %@ cookies : %@", [httpResp allHeaderFields], cookies);
//
//        if (@available(iOS 11.0, *)) {
//            WKHTTPCookieStore *cookieStore = [WKWebsiteDataStore defaultDataStore].httpCookieStore;
//            for (NSHTTPCookie *cookie in cookies){
//                [cookieStore setCookie:cookie completionHandler:nil];
//            }
//        } else {
//            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[response URL] mainDocumentURL:nil];
//        }
        
        
      if(error){
          NSLog(@"setCookies error : %@",error);
          result(@(NO));
//        NSError *parseError = nil;
//        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
          
      } else {
          NSLog(@"setCookies success");
          result(@(YES));
      }
    }];
    [dataTask resume];
}

- (void)clearCookies:(FlutterResult)result {
  if (@available(iOS 9.0, *)) {
    NSSet<NSString *> *websiteDataTypes = [NSSet setWithObject:WKWebsiteDataTypeCookies];
    WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];

    void (^deleteAndNotify)(NSArray<WKWebsiteDataRecord *> *) =
        ^(NSArray<WKWebsiteDataRecord *> *cookies) {
          BOOL hasCookies = cookies.count > 0;
          [dataStore removeDataOfTypes:websiteDataTypes
                        forDataRecords:cookies
                     completionHandler:^{
                       result(@(hasCookies));
                     }];
        };

    [dataStore fetchDataRecordsOfTypes:websiteDataTypes completionHandler:deleteAndNotify];
  } else {
    // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
    NSLog(@"Clearing cookies is not supported for Flutter WebViews prior to iOS 9.");
  }
}

@end
